package com.uil.fileutil.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class FileToBase64Converter2 {
    public static final String PREFIX = "D:\\桌面文件\\";

    public static void To(String sourceFolder, String outputFolder) {
        try {
            Files.walk(Paths.get(PREFIX + sourceFolder))
                    .filter(Files::isRegularFile)
                    .forEach(file -> {
                        try {
                            String base64String = encodeFileToBase64(file.toString());
                            String relativePath = (sourceFolder.isEmpty() ? file.toString() : file.toString().replaceFirst(sourceFolder, "")).replace(PREFIX, "");;
                            String outputFilePath = PREFIX + outputFolder + File.separator + relativePath + ".txt";
                            writeBase64StringToFile(base64String, outputFilePath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String encodeFileToBase64(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        return Base64.getEncoder().encodeToString(fileContent);
    }

    private static void writeBase64StringToFile(String base64String, String outputFilePath) throws IOException {
        File outputFile = new File(outputFilePath);
        outputFile.getParentFile().mkdirs();
        FileWriter writer = new FileWriter(outputFile);
        writer.write(base64String);
        writer.close();
    }
}
